package com.example.backed.security;

import com.example.backed.config.JwtConfig;
import com.example.backed.utils.JwtUtil;
import jakarta.servlet.FilterChain;
import jakarta.servlet.ServletException;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.web.authentication.WebAuthenticationDetailsSource;
import org.springframework.stereotype.Component;
import org.springframework.web.filter.OncePerRequestFilter;

import java.io.IOException;
import java.util.Arrays;
import java.util.List;

@Component
@RequiredArgsConstructor
@Slf4j
public class JwtAuthenticationFilter extends OncePerRequestFilter {

    private final JwtUtil jwtUtil;
    private final UserDetailsService userDetailsService;
    private final JwtConfig jwtConfig;

    private static final List<String> PUBLIC_PATHS = Arrays.asList(
        "/api/auth/",
        "/api/public/",
        "/api/categories/",
        "/api/files/",
        "/api/upload",
        "/api/group-buy/",
        "/swagger-ui.html",
        "/swagger-ui/",
        "/v3/api-docs/"
    );

    @Override
    protected boolean shouldNotFilter(HttpServletRequest request) {
        String path = request.getRequestURI();
        boolean shouldNotFilter = PUBLIC_PATHS.stream().anyMatch(path::startsWith);
        log.info("URI: {}, 是否跳过过滤: {}", path, shouldNotFilter);
        return shouldNotFilter;
    }

    @Override
    protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain filterChain)
            throws ServletException, IOException {
        
        String uri = request.getRequestURI();
        log.info("处理请求: {}", uri);
        
        final String authHeader = request.getHeader(jwtConfig.getHeader());
        log.info("认证头部: {}", authHeader);
        
        final String jwt;
        final String subject;

        if (authHeader == null || !authHeader.startsWith(jwtConfig.getTokenPrefix())) {
            log.warn("认证头部为空或格式不正确: {}", authHeader);
            filterChain.doFilter(request, response);
            return;
        }

        jwt = authHeader.substring(jwtConfig.getTokenPrefix().length());
        log.info("提取的JWT: {}", jwt);
        
        try {
            subject = jwtUtil.extractUsername(jwt);
            log.info("从JWT解析的subject: {}", subject);

            if (subject != null && SecurityContextHolder.getContext().getAuthentication() == null) {
                log.info("加载用户详情: {}", subject);
                UserDetails userDetails = this.userDetailsService.loadUserByUsername(subject);
                log.info("用户详情: {}, 角色: {}", userDetails.getUsername(), userDetails.getAuthorities());
                
                if (jwtUtil.validateToken(jwt, userDetails)) {
                    log.info("JWT验证成功");
                    UsernamePasswordAuthenticationToken authToken = new UsernamePasswordAuthenticationToken(
                            userDetails,
                            null,
                            userDetails.getAuthorities()
                    );
                    authToken.setDetails(new WebAuthenticationDetailsSource().buildDetails(request));
                    SecurityContextHolder.getContext().setAuthentication(authToken);
                    log.info("已设置认证上下文");
                } else {
                    log.error("JWT验证失败");
                }
            }
        } catch (Exception e) {
            log.error("JWT处理异常", e);
        }
        
        filterChain.doFilter(request, response);
    }
} 